package net.adst.ui.mainframe.tabs.nanemTap;

import net.adst.beans.NaemTec;
import net.adst.resources.Constants;
import net.adst.resources.VariableNames;
import net.adst.util.DataManager;
import net.adst.util.GBC;
import net.adst.util.NaemTecCellRender;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: alekseipot
 * Date: 02.11.12
 * Time: 6:55
 * To change this template use File | Settings | File Templates.
 */
public class DetailedTableNaemPanel extends JPanel {

    private JTable detailedTable;

    public DetailedTableNaemPanel() {
        setLayout(new GridBagLayout());
        addDetTable();
    }

    private void addDetTable() {
        DefaultTableModel model = new DefaultTableModel( //NotEditableDefaultTableModel
                new Object[][]{
                },
                Constants.NAEM_НEADER
        ) {
            @Override
            public boolean isCellEditable(final int row, final int col) {
                if (col == 10 || col == 14 || col == 15 || col == 19) {
                    return false;
                }
                return true;
            }
        };
        detailedTable = new JTable(model);
        detailedTable.setRowHeight(Constants.TABLE_ROW_HEIGHT);
        detailedTable.getTableHeader().setReorderingAllowed(false);
        detailedTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting())
                    return;
                ListSelectionModel lsm = (ListSelectionModel) e.getSource();

                final JTextArea description = (JTextArea) DataManager.getObject(VariableNames.COMMENT_TEXT);

                if (lsm.isSelectionEmpty()) {
                    description.setText("");
                    description.setEnabled(false);
                    description.setEditable(false);
                    ((JButton) DataManager.getObject(VariableNames.UI_TOP_PANEL_REMOVE_BUTTON)).setEnabled(false);
                    ((JButton) DataManager.getObject(VariableNames.UI_TOP_PANEL_MARK_NAEM_PAID_NAM_BUTTON)).setEnabled(false);
                    ((JButton) DataManager.getObject(VariableNames.UI_TOP_PANEL_MARK_NAEM_PAID_NAM_OK_BUTTON)).setEnabled(false);
                    ((JButton) DataManager.getObject(VariableNames.UI_TOP_PANEL_MARK_NAEM_PAID_NAM_NADO_BUTTON)).setEnabled(false);
                } else {
                    ((JButton) DataManager.getObject(VariableNames.UI_TOP_PANEL_REMOVE_BUTTON)).setEnabled(true);
                    ((JButton) DataManager.getObject(VariableNames.UI_TOP_PANEL_MARK_NAEM_PAID_NAM_BUTTON)).setEnabled(true);
                    ((JButton) DataManager.getObject(VariableNames.UI_TOP_PANEL_MARK_NAEM_PAID_NAM_OK_BUTTON)).setEnabled(true);
                    ((JButton) DataManager.getObject(VariableNames.UI_TOP_PANEL_MARK_NAEM_PAID_NAM_NADO_BUTTON)).setEnabled(true);
                    final JTable sumTable = (JTable) DataManager.getObject(VariableNames.UI_NAEM_SUM_TABLE);
                    sumTable.getSelectionModel().clearSelection();
                    final int selectedRow = lsm.getMinSelectionIndex();
                    DataManager.setObject(VariableNames.NAEM_SELECTED_ROW, (Integer) selectedRow);
                    int col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[19]);
                    if (selectedRow > -1) {
                        if (detailedTable.getValueAt(selectedRow, col).equals("*")) {
                            ArrayList<NaemTec> rows = (ArrayList<NaemTec>) DataManager.getObject(VariableNames.TEC_NAEM_USING_ROWS);
                            NaemTec tec = rows.get(detailedTable.getSelectedRow());
//                            Integer tecId = Integer.valueOf(detailedTable.getValueAt(, Constants.NAEM_НEADER.length - 1).toString());
//                            for (NaemTec item : rows) {
//                                if (item.getRowInFile() == tecId) {
//                                    tec = item;
//                                    break;
//                                }
//
//                            }
                            description.setText(tec.getComment());
                            description.setEnabled(true);
                            description.setEditable(true);
                        } else {
                            description.setEnabled(true);
                            description.setEditable(true);
                            description.setText("");
                        }
                    } else {
                        return;
                    }
                }
            }
        });
        detailedTable.setDefaultRenderer(Object.class, new NaemTecCellRender());
        detailedTable.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("tableCellEditor") && evt.getNewValue() != null) {
                    ((JButton) DataManager.getObject(VariableNames.UI_TOP_PANEL_SAVE_BUTTON)).setEnabled(false);
                }
                if (evt.getPropertyName().equals("tableCellEditor") && evt.getNewValue() == null) {
                    ((JButton) DataManager.getObject(VariableNames.UI_TOP_PANEL_SAVE_BUTTON)).setEnabled(true);
                }
            }
        });

        model.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                if (e.getType() != 1 && e.getType() != -1) {
                    int row = e.getFirstRow();
                    JButton editButton = (JButton) DataManager.getObject(VariableNames.UI_TOP_PANEL_SAVE_BUTTON);
                    editButton.setEnabled(true);

                    if (e.getColumn() == 6 && !detailedTable.getValueAt(row, 6).toString().isEmpty()) {
                        try {
                            Double price = Double.valueOf(detailedTable.getValueAt(row, 6).toString());
                            if (!detailedTable.getValueAt(row, 9).toString().isEmpty()) {
                                detailedTable.setValueAt(new BigDecimal(Double.valueOf(detailedTable.getValueAt(row, 9).toString()) * price).setScale(2, RoundingMode.HALF_DOWN).toString(), row, 10);
                            }
                        } catch (IllegalArgumentException ex) {
                            detailedTable.setValueAt("", row, 6);
                        }

                    }
                    if (e.getColumn() == 9 && !detailedTable.getValueAt(row, 9).toString().isEmpty()) {
                        try {
                            Double hours = Double.valueOf(detailedTable.getValueAt(row, 9).toString());
                            if (!detailedTable.getValueAt(row, 6).toString().isEmpty()) {
                                detailedTable.setValueAt(new BigDecimal(Double.valueOf(detailedTable.getValueAt(row, 6).toString()) * hours).setScale(2, RoundingMode.HALF_DOWN).toString(), row, 10);
                            }
                        } catch (IllegalArgumentException ex) {
                            detailedTable.setValueAt("", row, 9);
                        }

                    }

                    if (e.getColumn() == 12 && !detailedTable.getValueAt(row, 12).toString().isEmpty()) {
                        try {
                            Double price = Double.valueOf(detailedTable.getValueAt(row, 12).toString());
                            if (!detailedTable.getValueAt(row, 13).toString().isEmpty()) {
                                detailedTable.setValueAt(new BigDecimal(Double.valueOf(detailedTable.getValueAt(row, 13).toString()) * price).setScale(2, RoundingMode.HALF_DOWN).toString(), row, 14);
                            }
                        } catch (IllegalArgumentException ex) {
                            detailedTable.setValueAt("", row, 12);
                        }

                    }
                    if (e.getColumn() == 13 && !detailedTable.getValueAt(row, 13).toString().isEmpty()) {
                        try {
                            Double hours = Double.valueOf(detailedTable.getValueAt(row, 13).toString());
                            if (!detailedTable.getValueAt(row, 12).toString().isEmpty()) {
                                detailedTable.setValueAt(new BigDecimal(Double.valueOf(detailedTable.getValueAt(row, 12).toString()) * hours).setScale(2, RoundingMode.HALF_DOWN).toString(), row, 14);
                            }
                        } catch (IllegalArgumentException ex) {
                            detailedTable.setValueAt("", row, 13);
                        }

                    }

                    if (e.getColumn() == 17) {
                        try {
                            Double arenda = !detailedTable.getValueAt(row, 17).toString().isEmpty() ? Double.valueOf(Double.valueOf(detailedTable.getValueAt(row, 17).toString())) : new Double("0");
                        } catch (IllegalArgumentException ex) {
                            detailedTable.setValueAt("", row, 17);
                        }

                    }

                    if (e.getColumn() == 18) {
                        try {
                            Double prorab = !detailedTable.getValueAt(row, 18).toString().isEmpty() ? Double.valueOf(Double.valueOf(detailedTable.getValueAt(row, 18).toString())) : new Double("0");
                        } catch (IllegalArgumentException ex) {
                            detailedTable.setValueAt("", row, 18);
                        }

                    }

                    if (e.getColumn() == 6 || e.getColumn() == 9 || e.getColumn() == 12 || e.getColumn() == 13 || e.getColumn() == 17 || e.getColumn() == 18) {
                        Double priceOut = !detailedTable.getValueAt(row, 6).toString().isEmpty() ? Double.valueOf(Double.valueOf(detailedTable.getValueAt(row, 6).toString())) : new Double("0");
                        Double hourOut = !detailedTable.getValueAt(row, 9).toString().isEmpty() ? Double.valueOf(Double.valueOf(detailedTable.getValueAt(row, 9).toString())) : new Double("0");
                        Double priceIn = !detailedTable.getValueAt(row, 12).toString().isEmpty() ? Double.valueOf(Double.valueOf(detailedTable.getValueAt(row, 12).toString())) : new Double("0");
                        Double hourIn = !detailedTable.getValueAt(row, 13).toString().isEmpty() ? Double.valueOf(Double.valueOf(detailedTable.getValueAt(row, 13).toString())) : new Double("0");
                        Double arenda = !detailedTable.getValueAt(row, 17).toString().isEmpty() ? Double.valueOf(Double.valueOf(detailedTable.getValueAt(row, 17).toString())) : new Double("0");
                        Double prorab = !detailedTable.getValueAt(row, 18).toString().isEmpty() ? Double.valueOf(Double.valueOf(detailedTable.getValueAt(row, 18).toString())) : new Double("0");
                        detailedTable.setValueAt(priceOut * hourOut - priceIn * hourIn - arenda - prorab, row, 15);
                    }

                }
            }
        }
        );

//        TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>(model);
//        int col = 0;
//        sorter.setComparator(col, new Comparator<String>() {
//            public int compare(String dt1, String dt2) {
//                //ORS-20 fix SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
//                SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
//                int res = 0;
//                try {
//                    Date date1 = sdf.parse(dt1);
//                    Date date2 = sdf.parse(dt2);
//                    res = date1.compareTo(date2);
//                } catch (ParseException e) {
//                    // res = 0;
//                }
//                return res;
//            }
//        });
//        detailedTable.getTableHeader().setReorderingAllowed(false);
//        detailedTable.setRowSorter(sorter);
        setWidth(detailedTable);
        JScrollPane scrollPane = new JScrollPane(detailedTable);
        DataManager.setObject(VariableNames.UI_NAEM_DETAILED_MODEL, model);
        DataManager.setObject(VariableNames.UI_NAEM_DETAILED_TABLE, detailedTable);
        detailedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        add(scrollPane, new GBC(0, 0).setFill(GBC.BOTH).setWeight(1, 1));
    }

    private void setWidth(JTable detailedTable) {
        // ORS-22
        int col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[0]);
        TableColumn column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(70);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[1]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(55);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[2]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(60);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[3]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(150);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[4]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(70);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[5]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(160);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[6]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(80);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[7]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(80);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[8]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(70);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[9]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(110);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[10]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(70);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[11]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(70);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[12]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(70);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[13]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(70);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[14]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(120);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[15]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(70);

        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[16]);
        column = detailedTable.getColumnModel().getColumn(col);
        column.setPreferredWidth(70);

//        col = detailedTable.getColumnModel().getColumnIndex(Constants.NAEM_НEADER[20]);
//        column = detailedTable.getColumnModel().getColumn(col);
//        column.setPreferredWidth(0);
//        column.setMaxWidth(0);
//        column.setMinWidth(0);

    }

}
